
//
//  LTFriendsViewController.m
//  LTChat
//
//  Created by apple on 4/21/14.
//  Copyright (c) 2014 fantasy. All rights reserved.
//

#import "LTFriendsViewController.h"
#import "LTMessageViewController.h"
#import "SearchFriendViewController.h"
#import "AppDelegate.h"
#import "ChatRoster.h"
#import "Storage.h"

@interface LTFriendsViewController ()
<
    XMPPStreamDelegate,
    XMPPRosterDelegate
>
{
    NSMutableArray *rosters;
    BOOL isEndPopulating;
    BOOL isUpdatedRosterList;
}
@end

@implementation LTFriendsViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        isUpdatedRosterList = NO;
    }
    return self;
}

-(void)dealloc
{
    [[[[self appDelegate] xmppChatManager] xmppRoster] removeDelegate:self];
    [[self xmppStream] removeDelegate:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    rosters = [[NSMutableArray alloc] init];
    [[self xmppStream] addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction:)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"测试" style:UIBarButtonItemStyleBordered target:self action:@selector(updateStatusInfo:)];
    
    [[[[self appDelegate] xmppChatManager] xmppRoster] addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    if ([[self xmppStream] isConnected]) {
        if (!isUpdatedRosterList) {
            isUpdatedRosterList = YES;
            [self queryRosterList];
        }
        
    }
}

-(NSString *)generateID {
    return @"rosterGenerateID";
}

-(void)queryRosterList {
    
//    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
//    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
//    XMPPJID *myJID = [self xmppStream].myJID;
//    [iq addAttributeWithName:@"from" stringValue:myJID.description];
//    [iq addAttributeWithName:@"to" stringValue:myJID.domain];
//    [iq addAttributeWithName:@"id" stringValue:[self generateID]];
//    [iq addAttributeWithName:@"type" stringValue:@"get"];
//    [iq addChild:query];
//    [[self xmppStream] sendElement:iq];
    
    XMPPIQ *iq = [XMPPIQ iqWithType:@"get"];
    [iq addAttributeWithName:@"from" stringValue:[[[self xmppStream] myJID] description]];
    [iq addAttributeWithName:@"id" stringValue:[self generateID]];
    NSXMLElement* element_query=[NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
    [iq addChild:element_query];
    [[self xmppStream] sendElement:iq];
}

-(void)searchAction:(UIBarButtonItem *)bar
{
    SearchFriendViewController *searchB = [[SearchFriendViewController alloc] init];
    [self.navigationController pushViewController:searchB animated:YES];
}

-(void)updateStatusInfo:(UIBarButtonItem *)bar
{
    XMPPPresence *presence = [XMPPPresence presence];
    NSXMLElement *element = [NSXMLElement elementWithName:@"status" stringValue:@"你好啊!"];
    [presence addChild:element];
    [[self xmppStream] sendElement:presence];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [rosters count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"reuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
    }
    ChatRoster *roster = [rosters objectAtIndex:indexPath.row];
    if ([roster.nickName length] > 0) {
        cell.textLabel.text = [roster nickName];
    } else {
        cell.textLabel.text = [roster user];
    }
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
    // Create the next view controller.
    LTMessageViewController *message = [[LTMessageViewController alloc] init];
    message.roster = [rosters objectAtIndex:indexPath.row];
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:message animated:YES];
}

-(AppDelegate *)appDelegate{
    
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(XMPPStream *)xmppStream{
    
    return [[[self appDelegate] xmppChatManager] xmppStream];
}

- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
//    NSLog(@"%s --> %@",__FUNCTION__,sender);
}

/**
 * Sent when a Roster Push is received as specified in Section 2.1.6 of RFC 6121.
 **/
- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterPush:(XMPPIQ *)iq
{
    NSLog(@"%s --> %@",__FUNCTION__,iq);
    ChatRoster *roster = [[ChatRoster alloc] initWithItem:[[iq elementForName:@"query"] elementForName:@"item"]];
    [rosters addObject:roster];
    NSLog(@"%@",rosters);
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}

-(BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    NSLog(@"%s ---> %@",__FUNCTION__,iq);
    //获取好友列表需要在此处理
//    if ([iq childCount] > 0) {
//        <#statements#>
//    }
    if ([iq childCount] > 0) {
        NSXMLElement *element_query = iq.childElement;
        if ([element_query.name isEqualToString:@"query"] && [[element_query xmlns] isEqualToString:@"jabber:iq:roster"]) {
            for (NSXMLElement *item in element_query.children) {
                ChatRoster *roster = [[ChatRoster alloc] initWithItem:item];
                [rosters addObject:roster];
            }
            [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
    }
    return YES;
}

///**
// * Sent when the initial roster is received.
// **/
//- (void)xmppRosterDidBeginPopulating:(XMPPRoster *)sender
//{
//    NSLog(@"%s --> %@",__FUNCTION__,sender);
//}
//
///**
// * Sent when the initial roster has been populated into storage.
// **/
//- (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender
//{
//    NSLog(@"friends : %@",rosters);
//    NSLog(@"%s --> %@",__FUNCTION__,sender);
//    [[self tableView] reloadData];
//    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
//}
//
///**
// * Sent when the roster receives a roster item.
// *
// * Example:
// *
// * <item jid='romeo@example.net' name='Romeo' subscription='both'>
// *   <group>Friends</group>
// * </item>
// **/
//- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterItem:(NSXMLElement *)item
//{
//    NSLog(@"%s --> %@",__FUNCTION__,item);
//    ChatRoster *roster = [[ChatRoster alloc] initWithItem:item];
//    [rosters addObject:roster];
//    NSLog(@"%@",rosters);
//}

-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    NSLog(@"%s --> %@",__FUNCTION__,message);
    ChatMessage *msg = [[ChatMessage alloc] initWithElement:message];
    NSLog(@"msg : %@",msg.body);
    [[Storage shareStance] saveMessageToDB:msg];
    
}

-(void)xmppStream:(XMPPStream *)sender didReceiveError:(DDXMLElement *)error
{
    NSLog(@"%s --> %@",__FUNCTION__,error);
}

-(void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    NSLog(@"%s : %@",__FUNCTION__,presence);
    //取得好友状态    available上线,away离开,do not disturb忙碌,unavailable下线.
    NSString *presenceType = [presence type];
    //当前用户
    NSString *userId = [[sender myJID] user];
    //在线用户
    NSString *presenceFromUser = [[presence from] user];
    if (![presenceFromUser isEqualToString:userId]) {
        //在线状态
        if ([presenceType isEqualToString:@"available"]) {
            NSLog(@"在线");
        } else if ([presenceType isEqualToString:@"unavailable"]) {
            NSLog(@"不在线");
        } else if ([presenceType isEqualToString:@"subscribe"]) {
            NSLog(@"presencetype : %@",presenceType);
            [[[[self appDelegate] xmppChatManager] xmppRoster] acceptPresenceSubscriptionRequestFrom:[presence from] andAddToRoster:YES];
        } else {
        }
    }
}

-(void)updateRosterList:(NSNotification *)notif {
    if (!isUpdatedRosterList) {
        isUpdatedRosterList = YES;
        [self queryRosterList];
    }
}

@end
